import json
import datetime

from run_gevent import celery
from app.chess import db
from app import dbop
from app import tools
from app.val_def import *


# from app import sync_data


@celery.task
def proc_every_minute():
    print("proc_every_minute:")


@celery.task
def delay_proc(flag):
    print("delay_proc:", flag)


def start_match(red_player_uid, black_player_uid, game_district_id):
    match_token = tools.get_random_str(32)

    dbop.ChessMatchDAO.update_record(None, {
        'red_player': red_player_uid,
        'black_player': black_player_uid,
        'token': match_token,
        'state': 'Ongoing',
        'create_time': datetime.datetime.now()
    })
    match = dbop.ChessMatchDAO.get_record_by_filter_key({
        'token': match_token
    })
    #
    for record_id in game_district_id:
        dbop.GameDistrictDAO.update_record(record_id, {
            'state': 'OnChess',
            'match_id': match.id,
            'update_time': datetime.datetime.now()
        })


@celery.task
def match_player():
    print("match_player:")
    while True:
        # 查看匹配的选项， 是要匹配真人还是匹配机器。
        red_pending_player = dbop.GameDistrictDAO.get_record_by_filter_key({
            'player': PLAYER_RED,
            'state': 'Pending',
        })
        black_pending_player = dbop.GameDistrictDAO.get_record_by_filter_key({
            'player': PLAYER_BLACK,
            'state': 'Pending',
        })

        match_machine = False
        if red_pending_player:
            param_json = tools.safe_json_loads(red_pending_player.param)
            opponent_select = param_json.get('opponent_select')
            if 'Machine' == opponent_select:
                start_match(red_pending_player.uid, -red_pending_player.uid, [red_pending_player.id, ])
                match_machine = True

        if black_pending_player:
            param_json = tools.safe_json_loads(black_pending_player.param)
            opponent_select = param_json.get('opponent_select')
            if 'Machine' == opponent_select:
                start_match(-black_pending_player.uid, black_pending_player.uid, [black_pending_player.id, ])
                match_machine = True

        if match_machine:
            continue

        if red_pending_player and black_pending_player:
            start_match(red_pending_player.uid, black_pending_player.uid,
                        [red_pending_player.id, black_pending_player.id])
        else:
            break
    # 检查需要机器人走棋的比赛
    # 找出所有红方为机器人的比赛
    records = dbop.ChessMatchDAO.get_red_machine_match()
    print("red machine match:", len(records))
    for match in records:
        last_move = dbop.ChessGameProcessDAO.get_match_last_record(match.id)
        if last_move is None or (last_move.seq % 2 == 0):
            # 机器人走子
            from app.machine import machine_move
            machine_move(match.id, 'R')

    # 找出所有黑方为机器人的比赛
    records = dbop.ChessMatchDAO.get_black_machine_match()
    print("black machine match:", len(records))
    for match in records:
        last_move = dbop.ChessGameProcessDAO.get_match_last_record(match.id)
        if last_move and (last_move.seq % 2 == 1):
            from app.machine import machine_move
            machine_move(match.id, 'B')

    delay_proc.apply_async(args=('123',), countdown=5)


